package com.ratingbay.console.social;

import java.util.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;

import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.twitter.api.CursoredList;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.social.twitter.api.TwitterProfile;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.CookieGenerator;

import com.ratingbay.cache.*;
import com.ratingbay.console.common.RatingBayConst;
import com.ratingbay.console.dataface.*;
import com.ratingbay.console.dataimpl.*;

public class TwitterUserSignin{
	private TwitterUserSignin(){

	}

	private static TwitterUserSignin self = null;
	public static TwitterUserSignin getInstance(){
		if(null == self){
			self = new TwitterUserSignin();
		}
		return self;
	}


	public void initUserData(Connection<?> connection, UserProfile profile){
	    String userName = profile.getUsername();
        String email = profile.getEmail();
		
		Twitter twitter = (Twitter) connection.getApi();

		List<ITwitterUser> followers = TwitterUserImplWithTwitterProfile.getITwitterUsers(twitter.friendOperations().getFollowers(userName));

		List<ITwitterUser> friends = TwitterUserImplWithTwitterProfile.getITwitterUsers(twitter.friendOperations().getFriends(userName));

		ITwitterUser twitterUser = TwitterUserImplWithTwitterProfile.getITwitterUser(twitter.userOperations().getUserProfile());

 		CacheManager cacheManager = CacheManager.getInstance();
 		Long userId = twitterUser.getId();

		if(!cacheManager.isExist(CacheCat.TWITTER_USER, "friends", userId)){
			cacheManager.put(CacheCat.TWITTER_USER, "friends", userId, (Object)friends);
		}

		if(!cacheManager.isExist(CacheCat.TWITTER_USER, "followers", userId)){
			cacheManager.put(CacheCat.TWITTER_USER, "followers", userId, (Object)followers);
		}

		ServletRequestAttributes attrs = 
            (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attrs.getRequest() ;
        HttpSession session = request.getSession();
        
        session.setAttribute(RatingBayConst.SESSION_KEY_USER, twitterUser);
        session.setAttribute(RatingBayConst.SESSION_KEY_TWITTER, twitter);

	}
}